/*
 * Copyright © 2024-2025 Wenze Wei
 *
 * This file is part of StadionOS.
 *
 * This Source Code Form is subject to the terms of the GNU General Public License, v. 2.0.
 * You can obtain a copy of the GPL at
 * https://www.gnu.org/licenses/old-licenses/gpl-2.0.html.
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
 * the specific language governing rights and limitations under the License.
 */

#include "../include/fsd.h"

/**
 * @brief Opens a file.
 *
 * This function opens the file 'file' with the given 'flags' and 'mode'.
 * It performs error checking on 'file' to ensure it is not NULL.
 *
 * @param file The path of the file to open.
 * @param flags The flags for opening the file.
 * @param mode The permissions for the new file.
 * @return ssize_t The file descriptor, or -1 on error.
 */
ssize_t Sopen(const char *file, int flags, mode_t mode) {
    if (file == NULL)
        return -1;

    ssize_t fd = syscall(SYS_open, file, flags, mode);  

    if (fd == -1)
        return -1;

    return fd;
}

/**
 * @brief Opens a file with a specified mode string (FOR SYSTEM COMPONENTS ONLY).
 *
 * This function opens the file specified by 'file' with the mode string 'mode' and 'permissions'.
 * It translates the mode string to the corresponding flags and opens the file.
 * IMPORTANT: This function is critical and should only be used by system components.
 *
 * @param file The path of the file to open.
 * @param mode The mode string for opening the file (e.g., "r", "w", "a").
 * @param permissions The permissions for the new file.
 * @return ssize_t The file descriptor, or -1 on error.
 */
ssize_t SXopen(const char *file, const char *mode ,mode_t permissions) {
    if (file == NULL)
        return -1;

    int flags = Sflags(mode);
    ssize_t fd = Sopen(file, flags, permissions);

    if (fd == -1)
        return -1;

    return fd;
}
